package com.pmy.controller;

import com.pmy.pojo.User;
import com.pmy.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    UserServiceImpl userService;
//    默认登录页
    @RequestMapping("/")
    public ModelAndView index(ModelAndView modelAndView, HttpServletRequest request, String openId) {
        return new ModelAndView("redirect:/toLogin.do");
    }
    @RequestMapping("/toLogin.do")
    public ModelAndView toLogin(ModelAndView modelAndView, Model model, HttpServletRequest request) {
        modelAndView.setViewName("login");
        return modelAndView;
    }
//    验证正确跳转用户页，错误重定向到登录页
    @RequestMapping("/verify")
    public String verify(User user,HttpServletRequest request){
        User loginUser = null;
//        如果session不为空，说明以及登录了，直接返回主界面
        if (request.getSession().getAttribute("loginUser") != null){
            return "homepage";
        }

//        向数据库中查询账号
        try {
        loginUser = userService.queryCodePassword(user.getUserCode(), user.getUserPassword());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (loginUser == null){
            return "login";
        }else {
            HttpSession session = request.getSession();
            session.setAttribute("loginUser",loginUser.getUserCode());
        }
        return "homepage";
    }

//    清空session注销登录,返回登录页
    @RequestMapping("/logOff")
    public String logOff(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("loginUser");
        System.out.println(session.getAttribute("loginUser"));
        return "login";
    }
}
